package cn.stronglink.esm27.collection.iot.devices.esm27.task;

import cn.stronglink.esm27.collection.iot.devices.esm27.request.entity.ESM27RequestMessageFactory;
import cn.stronglink.esm27.collection.netty.NettyServerHandler;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import cn.stronglink.esm27.collection.core.util.ByteUtil;
import cn.stronglink.esm27.collection.iot.devices.esm27.ESM27Server;

import java.net.InetSocketAddress;

public class PushWindTimer implements Runnable {
	private static Logger logger = LogManager.getLogger(PushGasTimer.class.getName());
	private ESM27Server esm27Server; // esm27服务器

	public PushWindTimer(ESM27Server server) {
		this.esm27Server=server;
	}

	@Override
	public void run() {
		try {
			if (esm27Server.isConnection()) {
				byte[] datas = new byte[] {(byte)0xFF, 0x05, 0x00, 0x42, (byte)0xA0};
				esm27Server.send(datas);
				logger.info("定时获取风向实时数据命令已发送:"+ByteUtil.byteArrToHexString(datas));

//				Thread.sleep(3000);
			}
			if (!NettyServerHandler.channelGroup.isEmpty()) {
				// 循环CHANNEL_MAP发送数据
				for (Channel channel : NettyServerHandler.channelGroup) {
					InetSocketAddress insocket = (InetSocketAddress) channel.remoteAddress();
					String clientIp = insocket.getAddress().getHostAddress();
					byte[] datas = new byte[] {(byte)0xFF, 0x05, 0x00, 0x42, (byte)0xA0};
					channel.writeAndFlush(Unpooled.copiedBuffer(datas));
					logger.info("IP:[" + clientIp + "]定时获取风向实时数据命令已发送:" + ByteUtil.byteArrToHexString(datas));
				}
			} else {
				logger.info("没有连接的TCP客户端");
			}
		} catch (Exception e) {
			logger.error(e);
		}
	}
}
